<script setup lang="jsx">
import {computed, inject, ref, watch} from "vue";
import {Message} from "@arco-design/web-vue";
import parcel from "@/api/document/parcel.js";

const visible = defineModel()
const originalData = inject('parcelData', [])
const getRecord = inject('getRecord')
const crudRef = inject('crudRef')
const updateData = ref({})
const type = ref('')
const form = ref({
  type:'',
  parcel:[],
})
const userData = ref([])
const list = computed(()=>userData.value.map(i=>{
  return {
    id:i.id,
    number:i.number,
    ext_number:i.ext_number
  }
}))
watch(()=>form.value.type,()=>{
  if(!originalData.value){
    return []
  }
    userData.value.length = 0
    userData.value = originalData.value.filter(i=> {
      switch (form.value.type){
        case 'resend':
          return i.status == 6
        case 'cancel':
          return i.status != 6
        default:
          return true;
      }
    }).map(i=>{
      return {
        id:i.id,
        number:i.number,
        ext_number:i.ext_number
      }
    })
})

watch(originalData, (v) => {
  if(!v){
    return
  }
  userData.value.length = 0
  userData.value.push(...JSON.parse(JSON.stringify(v)))
})

watch(visible, (v) => {
  if(!userData.value){
    return
  }
  userData.value.length = 0
  userData.value.push(...JSON.parse(JSON.stringify(userData.value)))
})
const update = async () => {
  if(!form.value.type){
    Message.error('请选择操作类型')
    return
  }
  if(!form.value.parcel.length){
    Message.error('请选择箱号')
    return
  }

  // todo 更新货箱后端
  if(typeof parcel[form.value.type] !== 'function'){
    Message.error('操作类型错误')
    return
  }
  let api = parcel[form.value.type]
  let res = await api({ids:form.value.parcel})
  if(!res.success){
    Message.error(res.message)
    return false;
  }
  Message.info(res.message)
  cancel()
  getRecord()
  crudRef.value.refresh()
  return true;
}
const cancel = ()=>{
  visible.value = false
  form.value.type = ''
  form.value.parcel = []
}
</script>

<template>
  <a-modal
      :visible="visible"
      title="取消/重新发货/移除"
      :destroyOnClose="true"
      :getContainer="false"
      @cancel="visible = false"
      @ok="update"
  >
    <div class="grid">
      <a-space class="w-full mb-5">
        <a-radio-group v-model="form.type" type="button" require>
          <a-radio value="cancel"  v-auth="['document:parcel:cancel']">取消</a-radio>
          <a-radio value="deletes" v-auth="['document:parcel:delete']">移除</a-radio>
          <a-radio value="resend"  v-auth="['document:parcel:resend']">重新发货</a-radio>
        </a-radio-group>
      </a-space>
      <select v-model="form.parcel" multiple class="h-full">
        <option v-for="item in list" :value="item.id">{{item.number}} - {{item.ext_number}}</option>
      </select>
    </div>
  </a-modal>
</template>

<style scoped>

</style>